#include "LinkList.h"

void InitLinkList(LinkList* list) {
    list->length = 0;
    list->head = (LNode*)malloc(sizeof(LNode) * InitSize);
    if (list->head == NULL) {
        printf("InitLinkList failed\n");
        exit(0);
    }
    list->tail = list->head; // Initialize tail to point to head
    list->head->next = NULL;  // Initialize head->next to NULL
}

int LengthLinkList(LinkList list) {
    return list.length;
}

void LocateElemLinkList(LinkList list, LNode node, int* e) {
    for (int i = 0; i < list.length; i++) {
        if (list.head[i].value == node.value) {
            *e = i;
            return;
        }
    }
}

void GetELemLinkList(LinkList list, int i, LNode* node) {
    if (list.head == NULL || i < 0 || i >= list.length) {
        printf("GetElemLinkList failed: index out of bounds\n");
        exit(0);
    }
}

void LinkListInsert(LinkList* list, int i, LNode e) {
    if (list == NULL || i < 0 || i > list->length) {
        printf("LinkListInsert failed: invalid position\n");
        exit(0);
    }
    if (list->length >= InitSize) {
        printf("LinkListInsert failed: list is full\n");
        exit(0);
    }
    for (int j = list->length; j > i; j--) {
        list->head[j] = list->head[j - 1];
    }
    list->head[i] = e;
    list->length++;
}

void LinkListDelete(LinkList* list, int i, LNode* e) {
    if (list == NULL || i < 0 || i >= list->length) {
        printf("LinkListDelete failed: invalid position\n");
        exit(0);
    }
    *e = list->head[i];
    for (int j = i; j < list->length - 1; j++) {
        list->head[j] = list->head[j + 1];
    }
    list->length--;
}

void PrintLinkList(LinkList list) {
    if (list.head == NULL) {
        printf("LinkList is empty\n");
        return;
    }
    for (int i = 0; i < list.length; i++) {
        printf("%d ", list.head[i].value);
    }
    printf("\n");
}

void IsEmptyLinkList(LinkList list) {
    if (list.length == 0) {
        printf("LinkList is empty\n");
    }
    else {
        printf("LinkList is not empty\n");
    }
}

void DestroyLinkList(LinkList* list) {
    if (list->head != NULL) {
        free(list->head);
        list->head = NULL;
    }
}